// jQuery Slider Plugin for the ESP platform
var espIsSearchPage = /page\/search/g.test(document.location.pathname);
var espIsProductPage = /invt/g.test(document.location.pathname);

ESPSlider = function(src, args) {
	this.src = src;
	this.args = args;
	this.init();
}

// master vars
ESPSlider.sliders = [];
ESPSlider.slider = null;
ESPSlider.sliderBtn = null;
ESPSlider.query = null;
ESPSlider.moved = null;
ESPSlider.minVal = null;
ESPSlider.maxVal = null;
ESPSlider.rangeMin = null;
ESPSlider.rangeMax = null;

PriceSliderFrom = null;
PriceSliderTo = null;


if (/icat\/clearance/g.test(document.location.pathname)) {
	// hide certain facets on clearance page
	LM.complete(function() {
		jQuery("div.termtext").each(function() {
			if (/^Clearance|^Dresses from|^Up to 50\% Off Selected Dresses|^Sale|^Holiday Shop|^Summer Occasion Wear/g.test(jQuery(this).text())) {
				jQuery(this).css("display", "none");
			}
		});
	});
}



jQuery.fn.espSlider = function(args) {
	jQuery(this).each(function() {
		var slider = new ESPSlider(this, args);
		ESPSlider.sliders.push(slider);
	});
	jQuery(document).mouseup(function() {
		if (ESPSlider.slider != null && ESPSlider.slider.args["mouseup"] != null) {
			var slider = ESPSlider.slider;
			var vars = [];
			for (var ii = 0; ii < slider.dragButtons.length; ii++) {
				// if slider has not moved get original value, otherwise calculate from position
				var left = parseInt(jQuery(slider.dragButtons[ii]).css("left"));
				var moved = jQuery(slider.dragButtons[ii]).attr("moved");
				if (moved == "false") {
					vars.push(slider.sliderValues[ii]);
				}
				else {
					vars.push(slider.getValueFromSliderPosition(left));
				}
			}
			if (vars.sort) {
				vars.sort(ESPSlider.sortNumber);
			}
			slider.args["mouseup"](vars); // call any custom functions along with vars
		}
		//ESPSlider.slider.showLabels(e);
		ESPSlider.slider = null;
		ESPSlider.sliderBtn = null;
		return true;
	});
	// IE6 breaks if mouseover is on document!
	var mmobj = jQuery.browser.msie && jQuery.browser.version == "6.0" ? jQuery("#bgcontent_graywhite") : jQuery(document);
	mmobj.mousemove(function(e) {
		if (ESPSlider.slider == null || ESPSlider.sliderBtn == null) return true;
		try {
			ESPSlider.slider.showLabels(e);
			var xPos = Math.min(Math.max(ESPSlider.slider.leftX + ESPSlider.sliderBtn.mouseOffset - ESPSlider.slider.buttonOffset, e.pageX), ESPSlider.slider.rightX - ESPSlider.slider.buttonOffset + ESPSlider.sliderBtn.mouseOffset);
			var left = xPos - ESPSlider.slider.leftX - ESPSlider.sliderBtn.mouseOffset;
			jQuery(ESPSlider.sliderBtn).css("left", left);
			var value = ESPSlider.slider.getValueFromSliderPosition(left);
			jQuery(".esp-slider-button-label", ESPSlider.sliderBtn).html(ESPSlider.slider.scaleSymbol + value);
			return false;
		}
		catch (ex) {
			return true;
		}
	});
	return this;
}



ESPSlider.prototype.init = function() {
	this.from = this.args["from"];
	this.to = this.args["to"];
	this.range = this.to - this.from;
	var priceHash = getHashPriceValues();
	if (priceHash != null) {
		var values = decodeURIComponent(priceHash).split(":");
		this.sliderValues = [values[0], values[1]];
	}
	else {
		this.sliderValues = this.args["sliderValues"];
	}
	if (ESPSlider.rangeMin != null && ESPSlider.rangeMax != null) {
		this.rangeValues = [parseInt(ESPSlider.rangeMin), parseInt(ESPSlider.rangeMax)]
	}
	else {
		this.rangeValues = this.args["rangeValues"];
	}
	if (this.rangeValues[0] == this.rangeValues[1]) this.rangeValues[0] = this.sliderValues[0];
	this.dragButtons = [];
	this.width = jQuery(this.src).width();
	this.leftX = parseInt(jQuery(this.src).offset().left);
	this.rightX = this.leftX + this.width;
	this.scaleSymbol = this.args["scaleSymbol"] || "";
	this.labelTimer = null;
	this.buttonOffset = (parseInt(this.args["buttonWidth"]) || 10) / 2;
	// validate range
	if (this.rangeValues[0] < this.sliderValues[0]) this.rangeValues[0] = this.sliderValues[0];
	if (this.rangeValues[1] > this.sliderValues[1]) this.rangeValues[1] = this.sliderValues[1];

	var self = this;
	var html = [];
	html.push("<div class=\"esp-slider\">");
	html.push("<div class=\"esp-slider-body\"></div>");
	html.push("<div class=\"esp-slider-scale\">");
	html.push("<span style=\"left: 0\">" + this.scaleSymbol + this.from + "</span>");
	html.push("<span style=\"right: 0\">" + this.scaleSymbol + this.to + "</span>");
	html.push("</div>");
	html.push("</div>");
	jQuery(this.src).html(html.join("")).mousedown(function(e) {
		var src = e.target || e.srcElement;
		if (src && src.className == "esp-slider-button") {
			src.mouseOffset = e.pageX - parseInt(jQuery(src).css("left")) - self.leftX;
			ESPSlider.sliderBtn = src;
			ESPSlider.slider = self;
			jQuery(ESPSlider.sliderBtn).attr("moved", true);
			return false;
		}
	});
	if (this.rangeValues.length == 2) {
		var fromTo = [];
		for (var ii = 0; ii < this.rangeValues.length; ii++) {
			var fraction = ((this.rangeValues[ii] - this.from) / this.range);
			var left = parseInt(fraction * this.width);
			fromTo.push(left);
		}
		jQuery(".esp-slider", this.src).append("<div class=\"esp-slider-range\" style=\"left: " + fromTo[0] + "px; width: " + (fromTo[1] - fromTo[0]) + "px\"></div>");
	}
	var ranges = [];
	if (this.sliderValues.length == 2) {
		var fromTo = [];
		for (var ii = 0; ii < this.sliderValues.length; ii++) {
			var fraction = ((this.sliderValues[ii] - this.from) / this.range);
			var left = parseInt(fraction * this.width) - this.buttonOffset;
			fromTo.push(left);
		}
		var btn1 = jQuery("<div class=\"esp-slider-button\" style=\"left: " + fromTo[0] + "px\"><span class=\"esp-slider-button-label\">" + this.scaleSymbol + this.sliderValues[0] + "</span></div>").get(0);
		jQuery(btn1).attr("moved", false);
		jQuery(".esp-slider", this.src).append(btn1);
		this.dragButtons.push(btn1);
		var btn2 = jQuery("<div class=\"esp-slider-button\" style=\"left: " + fromTo[1] + "px\"><span class=\"esp-slider-button-label\">" + this.scaleSymbol + this.sliderValues[1] + "</span></div>").get(0);
		jQuery(btn2).attr("moved", false);
		jQuery(".esp-slider", this.src).append(btn2).attr("moved", false);
		this.dragButtons.push(btn2);
	}
	jQuery(this.src).mouseover(function(e) {
		self.showLabels(e);
	}).mouseout(function(e) {
		self.hideLabels(e);
	});
}
ESPSlider.prototype.showLabels = function(e) {
	clearTimeout(this.labelTimer);
	jQuery(".esp-slider-button-label", this.src).animate({ opacity: 1 });
}

ESPSlider.prototype.hideLabels = function(e) {
	clearTimeout(this.labelTimer);
	var src = e.target || e.srcElement;
	if (jQuery(".esp-slider-button-label", this.src).css("opacity") == 1) {
		prototype = window.setTimeout(function() {
			//jQuery(".esp-slider-button-label", this.src).css("opacity", 0).css("display", "none");
			jQuery(".esp-slider-button-label", this.src).animate({ opacity: 0.2 }, 500);
		}, 1000);
	}
}

ESPSlider.prototype.getValueFromSliderPosition = function(left) {
	var fraction = (left + this.buttonOffset) / this.width;
	var val = parseInt((fraction * this.range)) + parseInt(this.from);
	if (val > this.to) val = this.to;
	if (val < this.from) val = this.from;
	return val;
}
ESPSlider.sortNumber = function(a, b) {
	return a - b;
}
ESPSlider.roundToNearest = function(num, nearest) {
	return parseInt(Math.round(num / nearest) * nearest);
}
ESPSlider.roundUpToNearest = function(num, nearest) {
	return parseInt(Math.ceil(num / nearest) * nearest);
}
ESPSlider.roundDownToNearest = function(num, nearest) {
	return parseInt(Math.floor(num / nearest) * nearest);
}
ESPSlider.queryStringValue = function(key) {
	if (ESPSlider.query == null) {
		ESPSlider.query = {};
		var query = window.location.search.substring(1);
		var keyValuePairs = query.split("&");
		for (ii = 0; ii < keyValuePairs.length; ii++) {
			var keyValue = keyValuePairs[ii].split("=");
			if (keyValue.length == 2) {
				ESPSlider.query[keyValue[0]] = keyValue[1];
			}
		}
	}
	return ESPSlider.query[key] || "";
}


//*********** UI *****************//

jQuery(document).ready(function() {
	// new alignment shouldn't need this event to mop up
	//espInitSearchItemHeights();


});

function espPreInit() {
	// category tree (dynamic var used for filtering on category)
	try {
		var ltree = document.getElementById("categorytree").value;
		var ctree = "";
		var espCats = ltree.split("|");
		var espCat = "";
		for (var ii = 0; ii < espCats.length; ii++) {
			if (espCats[ii] != "") {
				espCat = espCats[ii];
				if (ctree == "") {
					ctree = espCats[ii];
				}
				else {
					ctree += "/" + espCats[ii];
				}
			}
		}
		var ptree = "";
		var pCat = "";
		var pageName = "";
		try {
			var tmpCats = ctree.split("/");
			tmpCats.pop();
			ptree = tmpCats.join("/");
			pCat = tmpCats[tmpCats.length - 1];
		}
		catch (e) { }
		try {
			pageName = document.getElementById("pagename").value;
		}
		catch (e) { }
		LM.config("CategoryTree", ctree);
		LM.config("Category", espCat);
		LM.config("ParentCategoryTree", ptree);
		LM.config("ParentCategory", pCat);
		LM.config("PageName", pageName);
		LM.config("Currency", LM.Currency);
		//LM.Config = {
			//"CategoryTree": ctree,
			//"Category": espCat,
			//"ParentCategoryTree": ptree,
			//"ParentCategory": pCat,
			//"PageName": pageName,
			//"Currency": LM.Currency
        	//}
	}
	catch (e) { }
	
	// Get custom fields
	jQuery("input[data-esp-var]").each(function () {
		var name = jQuery(this).attr("data-esp-var");
		if (name != "") {
			LM.config(name, jQuery(this).val());
		}
	});
}

var isSlidersInit = false;
function espComplete() {
	// Initialise sliders
	try {
		if (typeof Venda.Widget.Slider != "undefined" || Venda.Widget.Slider) {
			var rviSlider = new Venda.Widget.Slider({
				sliderID: 'rvilist',
				maxNum: 30,
				displayCount: 4,
				slideAmtNum: 1,
				slideLeft: 'slideLeft',
				slideRight: 'slideRight',
				duration: 0.2
			});
			YAHOO.util.Event.onAvailable('relatedproductdetail', function() {
				rviSlider.init();
			});
		}
		var topsellerssliderSlide = Venda.Widget.Slider('topsellerssliderlist',30,4,1,'topsellerssliderLeft','topsellerssliderRight',0.3,0);
		YAHOO.util.Event.onAvailable('topsellersslider', topsellerssliderSlide.init, topsellerssliderSlide, true); 
		var bestsellerssliderSlide = Venda.Widget.Slider('bestsellerssliderlist',30,4,1,'bestsellerssliderLeft','bestsellerssliderRight',0.3,0);
		YAHOO.util.Event.onAvailable('bestsellersslider', bestsellerssliderSlide.init, bestsellerssliderSlide, true); 
	}
	catch (e) { }
	// initialise misc drop downs
	var currentUrl = window.location.pathname + window.location.search;
	try {
		//var sortDD = document.getElementById("sortby");
		//var sizeDD = document.getElementById("perpagedpd");
		//jQuery(sortDD).val(currentUrl);
		//jQuery(sizeDD).val(currentUrl);
		//if (sortDD.selectedIndex == -1) sortDD.selectedIndex = 0;
		//if (sizeDD.selectedIndex == -1) sizeDD.selectedIndex = 0;
	}
	catch (e) { }
	try {
		espInitSlider();
	}
	catch (e) { }
	// tidy swatches and drop downs
	try {
		jQuery("li.productSet").each(function() {
			var swatchQuery = jQuery("div.swatch", this);
			if (swatchQuery.length == 1) {
				swatchQuery.css("visibility", "hidden");
				jQuery("div.colour select", this).css("visibility", "hidden");
			}
		});
	}
	catch (e) { }
	// equal heights
	espNudgeCount = 0;
	espInitSearchItemHeights();
}

var espNudgeApplied = false;
var espNudgeCount;
function espInitSearchItemHeights() {
	try {
		espEqualiseHeights();
		return;
		//Venda.Platform.EqualHeight.init(["li.productSet .image", "li.productSet .esp_list_swatch", "li.productSet .productName", "li.productSet .invtdesc2", "li.productSet .esp_sizer", "li.productSet .buttons", "li.productSet .details", "li.productSet"]);
		// to fix alignment add 2 pixels onto max productSet height and resize ... this
		// should stop over alignment ... note we only over size 1 time
		if (espNudgeCount <= 2) {
			//if (!espNudgeApplied) {
			var espMaxHeight = 0;
			jQuery("li.productSet").each(function() {
				var espHeight = parseInt(jQuery(this).css("min-height"));
				if (espHeight > espMaxHeight) espMaxHeight = espHeight;
			});
			if (espMaxHeight > 0) {
				jQuery("li.productSet").css("min-height", (espMaxHeight + 2) + "px");
				espNudgeCount++;
				//espNudgeApplied = true;
			}
		}
	}
	catch (e) { }
}

function espEqualiseHeights() {
	var selectors = ["li.productSet .image", "li.productSet .esp_list_swatch", "li.productSet .productName", "li.productSet .invtdesc2", "li.productSet .esp_sizer", "li.productSet .buttons", "li.productSet .details", "li.productSet"];
	for (var ii = 0; ii < selectors.length; ii++) {
		var maxHeight = 0;
		var query = jQuery(selectors[ii]);
		query.each(function() {
			var obj = jQuery(this).get(0);
			if (obj.style && obj.style.removeProperty) {
				obj.style.removeProperty("height");
			}
			else if (obj.style && obj.style.removeAttribute) {
				obj.style.removeAttribute("height");
			}
			var height = jQuery(this).height();
			if (height > maxHeight) {
				maxHeight = height;
			}
		});
		if (maxHeight > 0) {
			query.css("height", maxHeight);
		}
	}
}

function espInitSlider() {
	var currencySymbol = jQuery("#esp-currency-symbol").text();
	var from = parseInt(jQuery("#esp-price-from").text());
	var to = parseInt(jQuery("#esp-price-to").text());
	if (from == to) from = 0;
	var min = ESPSlider.roundDownToNearest(from, 1);
	var max = ESPSlider.roundUpToNearest(to, 1);
	if (ESPSlider.queryStringValue("omin") != "" && ESPSlider.queryStringValue("omax") != "") {
		min = ESPSlider.queryStringValue("omin");
		max = ESPSlider.queryStringValue("omax");
	}
	var slider1 = min;
	var slider2 = max;
	if (ESPSlider.queryStringValue("esp_filter_sys_price") != "") {
		var priceFilter = ESPSlider.queryStringValue("esp_filter_sys_price").replace("%3a", ":").split(":");
		if (priceFilter.length == 2) {
			slider1 = parseInt(priceFilter[0]);
			slider2 = parseInt(priceFilter[1]);
		}
	}
	jQuery("#esp-price-slider").espSlider({
		from: min,
		to: max,
		sliderValues: [slider1, slider2],
		rangeValues: [from, to],
		scaleSymbol: currencySymbol,
		mouseup: function(vals) {
			ESPSlider.minVal = vals[0];
			ESPSlider.maxVal = vals[1];
			ESPSlider.moved = true;
			resetFiltersPrice("sys_price");
			return;

			var espUpdateLink = document.getElementById("esp-update-link");
			if (espUpdateLink != null) {
				var espMin = jQuery(espUpdateLink).attr("min");
				var espMax = jQuery(espUpdateLink).attr("max");
				//var espNewUrl = espUpdateLink.href.replace("filter_sys_price=" + espMin + "%3a" + espMax, "filter_sys_price=" + vals[0] + "%3a" + vals[1]);
				var espNewUrl = espUpdateLink.href.replace(/filter_sys_price=\d+%3a\d+/i, "filter_sys_price=" + vals[0] + "%3a" + vals[1])
				if (espNewUrl.indexOf("&omin=") == -1 && espNewUrl.indexOf("?omin=") == -1) {
					espNewUrl += "&omin=" + min;
				}
				if (espNewUrl.indexOf("&omax=") == -1 && espNewUrl.indexOf("?omax=") == -1) {
					espNewUrl += "&omax=" + max;
				}
				//alert("espNewUrl: " + espNewUrl);
				window.location.href = espNewUrl;
			}
		}
	});
	jQuery("#esp-clear-link").css("display", window.location.href.indexOf("_filter_sys_price=") == -1 ? "none" : "inline");
}

function espShowHideFacetGroup(link) {
	var container = jQuery(link).parent().prev();
	jQuery(container).toggle();
	var display = jQuery(container).css("display");
	if (display == "block") {
		jQuery(link).text("View Less");
	}
	else {
		jQuery(link).text("View All");
	}
}

function espDoSliderPrice(url) {
	this.href = url.replace('_filter_sys_price={{Min}}%3a{{Max}}', '_filter_sys_price=' + document.getElementById('from').value + ':' + document.getElementById('to').value);
}

function espSwatchClick(obj, title, image1, image2) {
	jQuery(obj).parents("li.productSet").each(function() {
		var showAltImages = jQuery(this).attr("showAltImages") == "true";
		jQuery("div.colour select", this).val(title);
		if (!showAltImages) {
			jQuery("img.picture", this).attr("src", image1);
		}
		jQuery("div.colour select", this).each(function() {
			espSetSizeDropDown(this);
		});
	});
}

function espShowBasketOptions(obj) {
	jQuery(obj).parents("li.productSet").each(function() {
		jQuery("span.price", this).attr("originalHtml", jQuery("span.price", this).html());
		jQuery(this).attr("showAltImages", true);
		jQuery("div.espAddToBasket", this).slideUp();
		jQuery("div.espAddNow", this).slideDown();
		jQuery("div.colour select", this).each(function() {
			espSetSizeDropDown(this);
		});
	});
	espShowAddNow(obj);
}

function espValidateForm(event, obj) {
	var form = jQuery(obj).parents("form").first()
	var sizeQuery = jQuery("div.size select", form);
	if (sizeQuery.length == 1) {
		var size = sizeQuery.val();
		if (size == "") {
			alert("Please choose a size and then click ADD NOW");
			return false;
		}
	}	
	var sku = jQuery("input[name='ivref']", form).val();
	espAddToBasket(event, sku);
	return false;
}

function espAddToBasket(e, sku) {
	clickedID = "espaddproduct" + sku;
	formID = "espaddproductform" + sku;
	var msgID = "espaddedmsg" + sku;
	YAHOO.util.Event.stopEvent(e); // suppress form submit
	if (document.getElementById('popupcart_panel') != null) {
		// animation variables to send to UpdateMinicart.js
		// if this variable is blank, then no colour animation will occur
		if (Venda.Widget.MinicartPopup.tags.fromcolor != "" && Venda.Widget.MinicartPopup.tags.frombgrcolor == "") {
			var minicartColors = {
				color: { from: Venda.Widget.MinicartPopup.tags.fromcolor, to: Venda.Widget.MinicartPopup.tags.tocolor }
			};
		}
		else if (Venda.Widget.MinicartPopup.tags.fromcolor == "" && Venda.Widget.MinicartPopup.tags.frombgrcolor != "") {
			var minicartColors = {
				backgroundColor: { from: Venda.Widget.MinicartPopup.tags.frombgrcolor, to: Venda.Widget.MinicartPopup.tags.tobgrcolor }
			};
		}
		else if (Venda.Widget.MinicartPopup.tags.fromcolor != "" && Venda.Widget.MinicartPopup.tags.frombgrcolor != "") {
			var minicartColors = {
				color: { from: Venda.Widget.MinicartPopup.tags.fromcolor, to: Venda.Widget.MinicartPopup.tags.tocolor },
				backgroundColor: { from: Venda.Widget.MinicartPopup.tags.frombgrcolor, to: Venda.Widget.MinicartPopup.tags.tobgrcolor }
			};
		}
		else {var minicartColors = "";}
		
		highlightItems = new YAHOO.util.ColorAnim('updateItems', minicartColors, Venda.Widget.MinicartPopup.tags.fromtoduration);
		highlightTotal = new YAHOO.util.ColorAnim('updateTotal', minicartColors, Venda.Widget.MinicartPopup.tags.fromtoduration);
			
		// find original source so you can restore it, make this variable global so UpdateMinicart.js can use it
		var buttonID = document.getElementById(clickedID);
		originalsrc = buttonID.src;
		if (YAHOO.util.Dom.hasClass(clickedID,"preorder")) {
			buttonID.src='/content/ebiz/'+ Venda.Widget.MinicartPopup.tags.bsref +'/resources/images/bt_pleasewait_sm.gif'; // change the add to basket image so the user knows something is happening
		}
		else{
			buttonID.src='/content/ebiz/'+ Venda.Widget.MinicartPopup.tags.bsref +'/resources/images/bt_pleasewait.gif'; // change the add to basket image so the user knows something is happening
		}
		
		// change layout field so that the response loaded in the div shows the relevant message
		document.getElementById(formID).layout.value = 'cartresponse';
		if (typeof document.getElementById(formID).curlayout != 'undefined') {
			// if there is a curlayout field change the value to cartresponse
			document.getElementById(formID).curlayout.value = 'cartresponse';
		};

		Venda.Widget.MinicartPopup.panelHeight = document.getElementById('popupcart_panel').offsetHeight; // original height of popup before cart updated

		ajaxFunction(Venda.Widget.MinicartPopup.tags.formaction, msgID, formID, function() {
			//leave this as an inserted script as it relies on loaded IDs from invt/addtocart_response
			insertScript('/venda-support/js/Venda/Widget/UpdateMinicart.js',formID);
			// now update and open the minicart, in that order
			ajaxFunction('/page/home&layout=minicart_detail', 'popupcart', undefined, function() { //we update cartwrapper so that static minicart detail will update
				if (Venda.Widget.MinicartPopup.windowsettings.milliseconds != ""){
					// reset the timer if automatic close is enabled
					clearTimeout(popupTimerId);
				};
				Venda.Widget.MinicartPopup.openAnim();
				Venda.Widget.MinicartPopup.highlightAdded();
				// reset form fields that were set by JS
				document.getElementById(formID).layout.value = '';
				document.getElementById(formID).ex.value = 'co_disp-shopc';
			});
			
			jQuery("html, body").animate({scrollTop: 0}, "slow");
			
			// locayta tracking
			var evt = e || window.event;
			var target = evt.target || evt.srcElement;
			LM.addBasketItem({ sku: sku, qty: 1 }, target);
			LM.getData();
		});
	}
	else {
		alert('Too much hurry to hit the button!!!');
	}
}

function espSetSizeDropDown(obj) {
	jQuery(obj).parents("li.productSet").each(function() {
		var data = eval(jQuery(":selected", this).attr("data"));
		var mediaUrl = jQuery(":selected", this).attr("mediaurl");
		var optHtml = "";
		var showAltImages = jQuery(this).attr("showAltImages") == "true";
		for (var ii = 0; ii < data.length; ii++) {
			var dataItem = data[ii];
			optHtml += "<option value=\"" + dataItem[1] + "\" price=\"" + dataItem[2] + "\">" + dataItem[1] + "</option>";
		}
		jQuery("div.size select", this)
			.children()
			.remove()
			.end()
			.append("<option value=\"\">UK Size</option>" + optHtml);
		jQuery("div.size select", this).each(function() {
			espOnSizeSelect(this);
		});
		if (showAltImages && mediaUrl != "") {
			jQuery("img.picture", this).attr("src", mediaUrl);
		}
	});
}
function espOnSizeSelect(select) {
	if (select.selectedIndex > 0) {
		
		//var currencySymbol = LM.Currency == "EUR" ? "&euro;" : "&pound;";
		
		var currencySymbol= new String();
		
		switch(LM.Currency){
		case ("GBP"):currencySymbol="&pound;";
		break;
		case ("EUR"):currencySymbol="&euro;";
		break;
		case ("USD"):currencySymbol="US&#36;";
		break;
		case ("CAD"):currencySymbol="C&#36;";
		break;	
		case ("AUD"):currencySymbol="AU&#36;";
		break;
		case ("NZD"):currencySymbol="NZ&#36;";
		break;
		default : currencySymbol="&pound;";
		break;			

		}

		var option = select.options[select.selectedIndex];
		var price = parseFloat(jQuery(option).attr("price"));
		jQuery(select).parents("li.productSet").each(function() {
			jQuery("span.price", this).html(currencySymbol + price.toFixed(2));
		});
	}
	else {
		jQuery(select).parents("li.productSet").each(function() {
			jQuery("span.price", this).html(jQuery("span.price", this).attr("originalHtml"));
		});
	}
}
function espShowAddNow(obj) {
	jQuery(obj).parents("li.productSet").each(function(idx) {
		jQuery("p.invtdesc2", this).hide();
		jQuery("div.esp_options", this).show();
		jQuery("div.addNow", this).show();
		jQuery("div.addToBasket", this).hide();
		jQuery("div.colour select", this).each(function() {// if colour contains only 1 item ... hide
			if (jQuery(this).children().length < 2) {
				//jQuery(this).css("display", "none");
			}
		});
	});
	if (typeof (Venda.Platform.EqualHeight) == "function") {
		espInitSearchItemHeights();
	}
}

function espCheckForm(obj) {
	jQuery(obj).parents("li.productSet").each(function(idx) {
	});
	return false;
}


//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
// Multi-select javascript
//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
LM.load(function() {
	//jQuery("div[lmzone]").html("<img src=\"" + LM.Domain + "/data/6a1e78fa-fbb8-431d-aa36-ae9169ae6697/support/loading.gif\" style=\"vertical-align: middle\" /> Loading, please wait...");
	var IEVersion = getIEVersionNumber();
	var lmzone = jQuery("div[lmzone][facetdomid][filterdomid]").get(0);
	jQuery(lmzone).css("clear", "both");
	var zoneHtml = jQuery(lmzone).html();
	if (jQuery("#espGreyOut").length == 0) jQuery(lmzone).html("<div style=\"" + (zoneHtml == "" ? "position:relative;" : "position: absolute;") + "left: 240px; margin-top: 70px;  width: 180px;\"><img src=\"" + LM.Domain + "/data/6a1e78fa-fbb8-431d-aa36-ae9169ae6697/support/loading.gif\" style=\"float: left;\"><div style=\"float: right; line-height: 32px;  font-size: 14px;\">Loading please wait...</div></div><div id=\"espGreyOut\" style=\"background-color:white; filter:alpha(opacity=30); opacity:0.3; -moz-opacity:0.30; z-index:20; height:100%; width:100%; background-repeat:no-repeat; background-position:center;" + (IEVersion != 0 && IEVersion <= 8 ? "position:relative;" : "") + "\">" + zoneHtml + "</div>");

	//Get hash key values
	var hashKeyValues = LM.getHashKeyValues();

	currentField = decodeURIComponent(getCurrentField());
	var hashField = "";
	var hashCount = 0;
	var hashPriceValues = getHashPriceValues();
	jQuery("a[data-checked]")
		.each(function() {
			if (jQuery(this).attr("data-field") != currentField && jQuery(this).attr("data-checked") != "true") {
				jQuery(this)
					.attr("data-enabled", "false")
					.addClass("tV2NoStock")
					.attr("style", "color: #c4c4c4; border:none");
			}
			if (jQuery.inArray(LM.QueryPrefix + "filter_" + jQuery(this).attr("data-field") + "=" + jQuery(this).attr("data-value"), hashKeyValues) == -1 && jQuery.inArray(LM.QueryPrefix + "filter_" + encodeURIComponent(jQuery(this).attr("data-field")) + "=" + encodeURIComponent(jQuery(this).attr("data-value")), hashKeyValues) == -1) {
				jQuery(this).attr("data-checked", "false");
			}
			else {
				jQuery(this)
					.attr("data-checked", "true")
					.attr("data-enabled", "true")
					.removeAttr("style")
					.removeClass("tV2NoStock");
				if (jQuery(this).attr("data-field") != hashField) {
					hashField = jQuery(this).attr("data-field");
					hashCount++;
				}
			}
			setIcon(jQuery(this).get(0));
			var parent = jQuery(this).parent();
			jQuery("span.tV2Stock", parent).text("(0)");
		});

	//If only one facet field selected, enable all options
	if (hashField != "" && hashCount == 1 && hashPriceValues == null) {
		jQuery("a[data-field=\"" + hashField + "\"]")
			.each(function() {
				jQuery(this)
					.attr("data-enabled", "true")
					.removeAttr("style")
					.removeClass("tV2NoStock");
				setIcon(jQuery(this).get(0));
			});
	}

	//Show individual clear and clear all links if facets selected
	jQuery(".taxonomyV2rclear").css("visibility", "hidden");
	jQuery("a[data-checked=true]")
		.each(function() {
			var id = "espClearFilter_" + jQuery(this).attr("data-field");
			document.getElementById(id).style.visibility = "visible";
			//jQuery("#" + id).css("visibility", "visible");
			jQuery("#espClearAllFilters").css("visibility", "visible");
		});
	if (hashPriceValues != null) {
		jQuery("#espClearFilter_sys_price").css("visibility", "visible");
		jQuery("#espClearAllFilters").css("visibility", "visible");
	}
});

var isSizeFacetSorted = false;

LM.complete(function() {
	var vals = [];
	jQuery("a[data-field=sys_price]").each(function() {
		vals.push(jQuery(this).attr("data-value").split(":"));
	});
	LM.registerFixedFacet("sys_price", vals);

	//Size vars
	var numericSizes = [];
	var alphaSizes = [];
	var teenSizes = [];
	var oneSize = [];
	var cupSizes = [];
	var alphaCupSizes = [];
	
	if (!isSizeFacetSorted) { 
		jQuery("a[data-field=" + (espIsSearchPage ? "Size" : "Size") + "]").each(function() {		
			var value = jQuery(this).attr("data-value");
			var parent = jQuery(this).parent();
			if (/^\d+$/.test(value) == true) {
				numericSizes.push(parent);
			}
			else if (value.toLowerCase().indexOf("yrs") != -1) {
				teenSizes.push(parent);
			}
			else if (value.toLowerCase().indexOf("cup") != -1) {
				alphaCupSizes.push(parent);
			}
			else if (/^(?=(?:.*?[0-9]){2})(?=(?:.*?[A-Za-z]){1})[A-Za-z0-9,.\-_]{3,}$/.test(value) == true) {
				cupSizes.push(parent);
			}
			else if (value.toLowerCase().replace(" ", "") == "onesize") {
				oneSize.push(parent);
			}
			else {
				alphaSizes.push(parent);
			}
		});
	
		numericSizes.sort(function(a, b) {
   			var compA = jQuery(jQuery(a).find("a").get(0)).attr("data-value");
   			var compB = jQuery(jQuery(b).find('a').get(0)).attr("data-value");
   			return compA - compB;
		});
		alphaSizes.sort(function (a, b) {
			var sizeArray = ["xs","s","m","l","xl","xxl","s/m","m/l"];
   			var compA = jQuery.inArray(jQuery(jQuery(a).find("a").get(0)).attr("data-value").toLowerCase(), sizeArray);
   			var compB = jQuery.inArray(jQuery(jQuery(b).find("a").get(0)).attr("data-value").toLowerCase(), sizeArray); 
   			return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
		});
		teenSizes.sort(function(a, b) {
   			var compA = jQuery(jQuery(a).find("a").get(0)).attr("data-value");
   			var compB = jQuery(jQuery(b).find('a').get(0)).attr("data-value");
   			return compA - compB;
		});
		cupSizes.sort(function (a, b) {
   			var compA = jQuery(jQuery(a).find("a").get(0)).attr("data-value");
   			var compB = jQuery(jQuery(b).find('a').get(0)).attr("data-value");
   			return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
		});
		alphaCupSizes.sort(function (a, b) {
   			var compA = jQuery(jQuery(a).find("a").get(0)).attr("data-value");
   			var compB = jQuery(jQuery(b).find('a').get(0)).attr("data-value");
   			return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
		});

		//var sizeList = [];
		var id = "espClearFilter_" + (espIsSearchPage ? "Size" : "Size");
		var sizeFacet = jQuery(document.getElementById(id)).next();
		jQuery.each(numericSizes, function(idx, itm) {
			//sizeList.push(itm);
			jQuery(sizeFacet).append(itm);
		});
		jQuery.each(alphaSizes, function(idx, itm) {
			//sizeList.push(itm);
			jQuery(sizeFacet).append(itm);
		});
		jQuery.each(teenSizes, function(idx, itm) {
			//sizeList.push(itm);
			jQuery(sizeFacet).append(itm);
		});
		jQuery.each(oneSize, function(idx, itm) {
			//sizeList.push(itm);
			jQuery(sizeFacet).append(itm);
		});
		jQuery.each(cupSizes, function(idx, itm) {
			//sizeList.push(itm);
			jQuery(sizeFacet).append(itm);
		});
		jQuery.each(alphaCupSizes, function(idx, itm) {
			//sizeList.push(itm);
			jQuery(sizeFacet).append(itm);
		});

		jQuery("ul.tV2-two-col").each(function() {	
			espSort2Column(this, jQuery(this).children());
		});

		isSizeFacetSorted = true;
	}
	
	// bind to form submit button for add to basket tracking on product detail page
	if (espIsProductPage) {
		jQuery("#addproduct").click(function () {
			var form = jQuery(this).parents("form").first();
			var esp_mainSku = jQuery("input[name='ivref']", form).val(); // Main product SKU
			var esp_buySku = jQuery("input[name='buy']", form).val();
			var esp_sku = esp_buySku == "" ? esp_mainSku : esp_buySku; // Purchased product SKU/Attribute SKU
			var esp_qty = jQuery("input[name='qty']", form).val(); // Quantity
			var esp_size = jQuery("input[name='att1']", form).val();
			var esp_colour = jQuery("input[name='att2']", form).val();
			if (esp_sku != "" && esp_colour != "" && esp_size != "" && esp_qty != "") {
				LM.addBasketItem({ "sku": esp_sku, "qty": esp_qty }, this);
			}
		});
	}
});

function espSort2Column(element, items) {
	for (i = 0; i < items.length - 1; i++) {
		if (i < Math.round(items.length / 2)) {
			jQuery(element).append(items[i]);
			jQuery(element).append(items[Math.round(items.length / 2) + i]);
		}
		else {
			break;
		}
	}
}

LM.syncFacets(function(args) {
	//Get facet data and enable facets
	var facets = args["facetData"];
	for (var field in facets) {
		var options = facets[field];
		for (var ii = 0; ii < options.length; ii++) {
			var option = options[ii];
			var count = 0;
			var value = null;
			if (option.length == 2) {
				count = option[0];
				value = option[1];
			}
			else if (option.length == 3) {
				count = option[0];
				value = option[1] + ":" + option[2];
			}
			if (value != null && count > 0) {
				jQuery("a[data-field=\"" + field + "\"][data-value=\"" + value + "\"]")
				.attr("data-enabled", "true")
				.removeClass("disabled")
				.removeAttr("style")
				.each(function() {
					setIcon(jQuery(this).get(0));
					var parent = jQuery(this).parent();
					jQuery("span.tV2Stock", parent).text("(" + jQuery(this).attr("data-count") + ")");
				});
			}
		}
	}

	try {
		//Get price range for price slider
		var priceOptions = facets["sys_price"];
		var priceOption = priceOptions[0];
		if (priceOption.length == 3) {
			ESPSlider.rangeMin = priceOption[1];
			ESPSlider.rangeMax = priceOption[2];
		}
		//alert(facets["sys_price"][0]);
		//alert(facets["sys_price"][1]);
	}
	catch (e) {}
});

var currentField = null;

//Get current field from hash, else return null
function getCurrentField() {
	var hashKeyValues = LM.getHashKeyValues();
	for (var i = 0; i < hashKeyValues.length; i++) {
		if (hashKeyValues[i].indexOf(LM.QueryPrefix + "cf=") == 0) {
			return hashKeyValues[i].split("=")[1];
		}
	}
	return null;
}

//Get price field values from hash, else return null
function getHashPriceValues() {
	var hashKeyValues = LM.getHashKeyValues();
	for (var i = 0; i < hashKeyValues.length; i++) {
		if (hashKeyValues[i].indexOf(LM.QueryPrefix + "filter_sys_price=") == 0) {
			return hashKeyValues[i].split("=")[1];
		}
	}
	return null;
}

//Reset function called by standard multi select links
function resetFilters(link) {
	var enabled = jQuery(link).attr("data-enabled") == "true";
	if (!enabled) return; // the option is disabled, take no action
	currentField = jQuery(link).attr("data-field");
	// custom logic for search which can only have 1 price band at a time
	// note: review when slider turned back on
	if (espIsSearchPage && currentField == "sys_price") {

		jQuery("a[data-field=sys_price][data-checked=true]").each(function() {
			jQuery(this).attr("data-checked", "false")
		});
		
	}
	if (espIsSearchPage && currentField == "sys_price_EUR") {
	    jQuery("a[data-field=sys_price_EUR][data-checked=true]").each(function() {
	        jQuery(this).attr("data-checked", "false");
	    });
	}
	// custom logic end
	toggleChecked(link);
	setIcon(link);
	
	setFilters(currentField);
}

//Reset filters function called by price slider
function resetFiltersPrice(field) {
	currentField = field;
	setFilters(field);
}

//Set filters
function setFilters(currentField) {
	var filters = {};
	var strFilters = "";
	//jQuery("a[data-checked]").each(function() {
		//var isChecked = 
	//});
	jQuery("a[data-checked=true]").each(function() {
		var field = jQuery(this).attr("data-field");
		var value = jQuery(this).attr("data-value");
		if (field && value) {
			strFilters += "&" + field + "=" + encodeURIComponent(value);
			if (!filters[field]) filters[field] = [];
			filters[field].push(value);
		}
	});
	
	
	//need to check and test
	//if(PriceSliderFrom != null && PriceSliderTo != null){
		//strFilters += "&sys_price=" + encodeURIComponent(PriceSliderFrom + ":" + PriceSliderTo);
		//if (!filters["sys_price"]) filters["sys_price"] = [];
		//filters["sys_price"].push(PriceSliderFrom + ":" +PriceSliderTo);
	//}
	//else if(PriceSliderFrom == null && PriceSliderTo== null ){
		//var priceHash = getHashPriceValues();
		//if (priceHash != null) {
			//strFilters += "&sys_price=" + encodeURIComponent(priceHash[0] + ":" + priceHash[1]);
			//if (!filters["sys_price"]) filters["sys_price"] = [];
			//filters["sys_price"].push(priceHash[0] + ":" + priceHash[1]);
		//}
	//}
	
	// commented this out until price slider is reintroduced
	/*if (ESPSlider.moved) {
		strFilters += "&sys_price=" + encodeURIComponent(ESPSlider.minVal + ":" + ESPSlider.maxVal);
		if (!filters["sys_price"]) filters["sys_price"] = [];
		filters["sys_price"].push(ESPSlider.minVal + ":" + ESPSlider.maxVal);
	}
	else if (ESPSlider.moved == null) {
		var priceHash = getHashPriceValues();
		if (priceHash != null) {
			strFilters += "&sys_price=" + encodeURIComponent(priceHash[0] + ":" + priceHash[1]);
			if (!filters["sys_price"]) filters["sys_price"] = [];
			filters["sys_price"].push(priceHash[0] + ":" + priceHash[1]);
		}
	}*/
	//alert(filters["Size"]);	
	LM.setFilters(filters, currentField);
	//LM.getData();
}


function applyPriceFilters(PriceFrom,PriceTo){

	PriceSliderFrom = PriceFrom;
	PriceSliderTo = PriceTo;
	//alert('pricefrom='+PriceFrom+' '+'priceto='+PriceSliderTo);
	resetFiltersPrice("sys_price");
	
}




//Clear all filters
function clearAllFilters() {
	LM.clearFilters();
	ESPSlider.moved = false;
}

//Clear individual filter
function clearFilter(field) {
	jQuery("a[data-checked=true][data-field=\"" + field + "\"]")
		.attr("data-checked", "false")
		.each(function() {
			setIcon(jQuery(this).get(0));
			
		});

	if (field == "sys_price") ESPSlider.moved = false;
	setFilters(field);
}

function toggleChecked(link) {
	var checked = jQuery(link).attr("data-checked") == "true";
	jQuery(link).attr("data-checked", !checked + "");
}

function setIcon(link) {
	var checked = jQuery(link).attr("data-checked") == "true";
	var enabled = jQuery(link).attr("data-enabled") == "true";
	if (enabled) {
		var src = "/content/ebiz/boohoo/resources/images/filter_" + (checked ? "selected" : "unselected") + ".png";
		jQuery("img", link).attr("src", src);
	}
	else {
		var src = "/content/ebiz/boohoo/resources/images/filter_unavailable.png";
		jQuery("img", link).attr("src", src);
	}
}

function sortProducts(select) {
	if (select.value != null && select.value != "") {
		var value = select.value.split(':');
		var sortField = value[0];
		var sortOrder = value[1];
		LM.setSortField(sortField, sortOrder);
	}
	else {
		LM.FacetMode = "data";
		LM.MergeHash = true;
		var hash = LM.getHash([LM.QueryPrefix + "sort", LM.QueryPrefix + "order", LM.QueryPrefix + "pg"]);
		LM.CurrentHash = "#" + hash;
		window.location.hash = hash;
		LM.getData();
	}
}

function setPage(page) {
	var top = jQuery(jQuery("div[lmzone][facetdomid][filterdomid]").get(0)).children()[0];
	var offset = jQuery(top).offset();
	if (getScrollTop() > offset.top) {
		jQuery("html, body").animate({ scrollTop: (offset.top - 100) }, "slow");
	}
	LM.setPage(page);
}

function getScrollTop(){
    if(typeof pageYOffset != 'undefined'){
        //most browsers
        return pageYOffset;
    }
    else{
        var B = document.body; //IE 'quirks'
        var D = document.documentElement; //IE with doctype
        D = (D.clientHeight) ? D : B;
        return D.scrollTop;
    }
}

function setHitsPerPage(select) {
	if (select.value != null && select.value != "") {
		var hash = LM.getHash([LM.QueryPrefix + "pg"]);
		LM.CurrentHash = "#" + hash;
		window.location.hash = hash;
		LM.setPageView(select.value);
	}
}

function setViewAll() {
	var hash = LM.getHash([LM.QueryPrefix + "pg"]);
	LM.CurrentHash = "#" + hash;
	window.location.hash = hash;
	LM.setPageView("viewall");
}

//Get IE version no.
function getIEVersionNumber() {
	var ua = navigator.userAgent;
	var MSIEOffset = ua.indexOf("MSIE ");

	if (MSIEOffset == -1) {
		return 0;
	} else {
		return parseFloat(ua.substring(MSIEOffset + 5, ua.indexOf(";", MSIEOffset)));
	}
}


 window.onresize = function() {
	// new alignment shouldn't need this event to mop up
	//espInitSearchItemHeights();
	
};

